import { ref, reactive } from 'vue'
import { logout, updataPassword } from '@/api/manager'
import { showModal, toast } from '@/composables/util'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
export const useRepassword = () => {
  // 实例化路由对象
  const router = useRouter()

  // 表单节点
  const formRef = ref(null)

  // 对话框组件节点
  const formDialogRef = ref(null)

  // 表单数据
  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: '',
  })

  // 获取仓库模块
  const userStore = useUserStore()

  // 解构数据
  const { user, asidWidth, zIndex } = storeToRefs(userStore)

  // 校验规则
  const rules = {
    oldpassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
    repassword: [{ required: true, message: '确认密码不能为空', trigger: 'blur' }],
  }

  // 提交修改
  const onSubmit = () => {
    formRef.value.validate(async val => {
      // 如果校验不通过
      if (!val) return false
      try {
        // 将按钮设置为加载状态
        formDialogRef.value.showLoading()
        await updataPassword(form)
        // 删除 pinia 数据
        userStore.userLogout()
        // 提示修改成功
        toast('修改密码成功！请重新登录')
        // 退回至登录页
        router.push('/login')
      } finally {
        // 关闭按钮加载状态
        formDialogRef.value.hideLoading()
      }
    })
  }

  // 退出登录
  const handleLogout = () => {
    showModal('确定要退出登录吗？')
      .then(() => {
        logout().finally(() => {
          // 删除 token 和 pinia 数据
          userStore.userLogout()
          // 跳转至登陆页
          router.push('/login')
          // 提示退出登录成功
          toast('退出登录成功')
        })
      })
      .catch(() => { })
  }

  // 刷新图标点击事件
  const handleRefresh = () => window.location.reload()

  // 显示改密对话框
  const openRePasswordForm = () => {
    formDialogRef.value.open()
    zIndex.value = -1
  }

  // 修改侧边栏宽度
  const setAsidWidth = () => userStore.setAsidWidth()

  return {
    user,
    formDialogRef,
    form,
    rules,
    formRef,
    asidWidth,
    onSubmit,
    openRePasswordForm,
    handleLogout,
    handleRefresh,
    setAsidWidth
  }
}
